/* Copyright (c) 2010, Peter Lényi */
/* Licensed under The BSD License. */

package gem.apps.fs.web;

import gem.apps.fs.engine.FileServer;
import gem.apps.fs.entities.FileMeta;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet class FileUploadfilePostServlet loads the uploaded file and stores it
 * along with its metadata.
 *
 * @author Peter Lényi
 * @version 20100509F2
 */
public class FileUploadfilePostServlet extends HttpServlet
{
    private static final String ADDRESS_FATAL = "/error/fatal/jsp";
    private static final String ADDRESS_WARNING = "/file/uploadfile/jsp";
    private static final String ADDRESS_SUCCESS = "/file/details/pre";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // prepare local variables
        boolean success = false;
        boolean validationError = false;
        List<String> messages = new ArrayList<String>();

        // prepare resources
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        FileServer fs = FileServer.getInstance();
        ResourceBundle gui = ResourceBundle.getBundle("Gui");

        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                // load request parameters
                FileMeta meta = (FileMeta) request.getSession().getAttribute("filemeta");
                List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
                FileItem file = null;
                String mime = null;
                for (FileItem fi : items) {
                    if (fi.isFormField()) {
                        if (fi.getFieldName().equals("form.mime")) {
                            mime = fi.getString();
                        }
                    }
                    else {
                        file = fi;
                    }};

                // validate data
                if (meta == null) {
                    messages.add(gui.getString("Gui.action.file.uploadmeta.err"));
                    validationError = true;
                }
                if (mime == null || mime.equals("")) {
                    messages.add(gui.getString("Gui.file.form.mime.err"));
                    validationError = true;
                }
                if (file == null) {
                    messages.add(gui.getString("Gui.file.form.file.err"));
                    validationError = true;
                }

                long uin = -1;
                if (!validationError) {
                    // execute logic
                    uin = fs.uploadFile(file, meta.getTitle(), meta.getComment(), meta.getOwner(), meta.getPassword(), mime);
                    if (uin < 0) {
                        messages.add(gui.getString("Gui.action.file.uploadfile.err"));
                    }
                    else {
                        messages.add(gui.getString("Gui.action.file.uploadfile.done"));
                        success = true;
                    }
                }

                // pass connection
                request.getSession().setAttribute("msg", messages);
                if (success && !validationError) {
                    request.getSession().removeAttribute("filemeta");
                    response.sendRedirect(getServletContext().getContextPath() + ADDRESS_SUCCESS + "?uin=" + uin);
                }
                else {
                    response.sendRedirect(getServletContext().getContextPath() + ADDRESS_WARNING);
                }
            }
            catch (FileUploadException ex) {
                response.sendRedirect(getServletContext().getContextPath() + ADDRESS_FATAL);
            }
        }
        else {
            response.sendRedirect(getServletContext().getContextPath() + ADDRESS_FATAL);
        }
    }
}
